import traceback

from pymysql import Connection
from pymysql.cursors import Cursor

import mysql_connect
from SnowflakeGenerator import SnowflakeGenerator

generator = SnowflakeGenerator(worker_id=1, datacenter_id=1)

def get_comment_ids():
    id_text: str = ""
    with open("other_files/zhihu_comment_ids.txt", 'r', encoding="utf-8") as r_file:
        id_text = r_file.read()
    id_list = [int(id.replace('"', "")) for id in id_text.split('\n')[1:-1]]
    return id_list


def get_one_user(comment_id: int, conn: Connection, cursor: Cursor):
    sql = f"""
        select username,image_url,introduction from zhihu_comment where id = {comment_id}
    """
    cursor.execute(sql)
    result = cursor.fetchone()
    # print(result)
    return result


def save_one_user(user_info: tuple, conn: Connection, cursor: Cursor):
    sql_check = f"""
        select
            count(id) as id_count
        from
            sys_user
        where 
            username = '{user_info[0]}'
    """
    cursor.execute(sql_check)
    is_check = True if cursor.fetchone()[0] == 1 else False
    if is_check:
        print("该用户已存在，无需插入，跳过")
        return
    sql_insert = """
        insert into
            sys_user
                (id,username,password_md5,salt,email,nickname,introduction,image_url,realname,status)
            values
                (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) 
        
    """
    insert_data = (
        generator.generate_id(),
        user_info[0],
        "f943c1d3a4fe7fbd5755327d1cb35145",
        "ef8e38a17e584e74b992c9fc3a800aeb",
        "123456@123.com",
        None,
        user_info[2],
        user_info[1],
        None,
        1
    )
    cursor.execute(sql_insert, insert_data)


def main():
    conn, cursor = mysql_connect.get_conn()

    try:
        id_list = get_comment_ids()
        for index, comment_id in enumerate(id_list):
            print(f"现在是第{index + 1}个，comment_id为{comment_id}，一共有{len(id_list)}个")
            try:
                user_info: tuple = get_one_user(comment_id, conn, cursor)
                save_one_user(user_info, conn, cursor)
            except:
                print("大失败")
                traceback.print_exc()
                continue

            if index % 1000 == 0 :
                print("1000个数据啦，开始提交！")
                conn.commit()
        conn.commit()



    except:
        print("巨大失败")
        traceback.print_exc()
    finally:
        cursor.close()
        conn.close()


if __name__ == "__main__":
    main()
